#!/usr/bin/python
#coding=utf-8
# Filename: login.py
# CreatedBy: ChenZhengguo 2011/12/6

import ConfigParser,urllib,urllib2,string
import msvcrt, sys, os, re
import mechanize


class ParseLogin:
    '''login with user and password'''
    def __init__(self, url=None, data={}, charset=None):
        self._url = url
        self._data = data
        self._charset = charset
        self._logined = False
        self._error = {}
        self._host = ''
        self._html = ''
        self._opener = None
    def login(self):
        '''login by urllib2'''
        params = urllib.urlencode(self._data)
        self._opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
        req = urllib2.Request(self._url,params)
        try :    
            res = self._opener.open(req)
        except urllib2.URLError, e:
            if hasattr(e, 'reason'):  
                self._error['code'] = e.reason[0]
                self._error['info'] = e.reason[1]
            elif hasattr(e, 'code'):  
                self._error['code'] = e.code
                self._error['info'] = ''               
            return False
        originHtml = res.read()
        self._host = req.get_type()+'://'+req.get_host()
        if(self._charset == None):
            p = re.compile(r'<meta\s*.*\scharset\=(.*)\s*\"\s*\/>',re.I)
            m = p.search(originHtml[0:295])
            if m :
                self._charset = m.group(1).lower()
            else :
                self._charset = 'utf-8'
        self._html = originHtml.decode(self._charset).encode('utf-8')
        #SG566 login
        if(self._html.find('window.top.location') != -1):
            self._logined = True
        return True
    def login2(self):
        '''login by mechanize'''
        params = urllib.urlencode(self._data)
        cookies = mechanize.CookieJar()
        self._opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
        self._opener.addheaders = [("User-agent", "Mozilla/5.0 (compatible; MyProgram/0.1)"),
                             ("From", "responsible.person@example.com")]        
        req = urllib2.Request(self._url,params)
        try:
            response = self._opener.open(self._url,params)  # POST
        except urllib2.URLError, e:
            if hasattr(e, 'reason'):  
                self._error['code'] = e.reason[0]
                self._error['info'] = e.reason[1]
            elif hasattr(e, 'code'):  
                self._error['code'] = e.code
                self._error['info'] = ''               
            return False
        originHtml = response.read()
        self._html = originHtml
        self._host = req.get_type()+'://'+req.get_host()
        if(self._charset == None):
            p = re.compile(r'<meta\s*.*\scharset\=(.*)\s*\"\s*\/>',re.I)
            m = p.search(originHtml[0:295])
            if m :
                self._charset = m.group(1).lower()
            else :
                self._charset = 'utf-8'
        
        #SG566 login
        if(self._html.find('window.top.location') != -1):
            self._logined = True
        return True
        
    def getInfo(self):
        return {
                'host'    : self._host,
                'error'   : self._error,
                'logined' : self._logined, 
                'url'     : self._url,
                'params'  : self._data,
                'charset' : self._charset,
                'html'    : self._html,
                }
    def getError(self):
        return self._error
    def getCharset(self):
        return self._charset
    def getOpener(self):
        return self._opener
    

##test 
#c = ParseLogin('https://10.66.2.100/user/login',
#{
#'user[account]' : 'weboper',
#'user[password]' : 'weboper',
#'lang' : 'zh_CN',
#'login' : '登  录',
#})
#if c.login() :
#    print 'Require Successfully'
#    if c.getInfo()['logined'] == True : 
#        print 'Logined'
#else :
#    print 'Require Failed'